//
//  NSString+Tool.m
//  RMEducation
//
//  Created by tongbinLi on 16/3/1.
//  Copyright © 2016年 tongbinLi. All rights reserved.
//

#import "NSString+Tool.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>

@implementation NSString(Tool)

- (NSString *)md532{
    const char *cStr = [self UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest );
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
        [result appendFormat:@"%02x", digest[i]];
    }
    return result;
}

- (NSString *)md516{
    //提取32位MD5散列的中间16位
    NSString *md532 = [self md532];
    NSString *result = [[md532 substringToIndex:24] substringFromIndex:8];//即9～25位
    return result;
}

-(NSString *)randomFileName:(NSInteger)number{
    
    if (number) {
        
        return [NSString stringWithFormat:@"%ld.%@",(long) (number + [[NSDate date] timeIntervalSince1970]),self];
    }else{
        
        return [self randomFileName];
    }
}

-(NSString *)randomFileName{
    
    return [NSString stringWithFormat:@"%ld.%@",(long)[[NSDate date] timeIntervalSince1970],self];
}

-(NSString *)pinyinFirstLetter {
    // 转成可变
    NSMutableString * mStr = [NSMutableString stringWithString:self];
    // 转为带声调的拼音
    CFStringTransform((CFMutableStringRef)mStr, NULL, kCFStringTransformMandarinLatin, NO);
    NSLog(@"转为带声调的拼音-->%@",mStr);
    
    // 再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)mStr, NULL, kCFStringTransformStripDiacritics, NO);
    NSLog(@"换为不带声调的拼音-->%@",mStr);
    
    // 转化为大写拼音
    NSString * pinyin  = [mStr capitalizedString];
    NSLog(@"大写拼音-->%@",pinyin);
    
    // 做判断找出所有小写字母
    NSMutableString * First = [NSMutableString stringWithString:pinyin];
    NSString * ABC =[[NSString alloc]init];
    
    for (int i = 0; i<First.length; i++) {
        unichar C = [First characterAtIndex:i];
        // 找出所有的大写字母
        if(C<= 'Z' && C>='A') {
            ABC = [ABC stringByAppendingFormat:@"%C",C];
            NSLog(@"剩下的大写字母 -----> %@",ABC);
        }
    }
    
    // 获取并返回首字母
    NSLog(@"所有首字母--->:%@",ABC);
    
    return ABC;
}

- (NSString *)md5String {
    const char *string = self.UTF8String;
    int length = (int)strlen(string);
    unsigned char bytes[CC_MD5_DIGEST_LENGTH];
    CC_MD5(string, length, bytes);
    return [self stringFromBytes:bytes length:CC_MD5_DIGEST_LENGTH];
}

- (NSString *)stringFromBytes:(unsigned char *)bytes length:(int)length {
    NSMutableString *mutableString = @"".mutableCopy;
    for (int i = 0; i < length; i++)
        [mutableString appendFormat:@"%02x", bytes[i]];
    return [NSString stringWithString:mutableString];
}
@end
